package vn.pdg.zoombie.bean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.Bitmap.CompressFormat;
import android.media.ExifInterface;

public class Utils {

	
    public static Bitmap decodeFile(File f,int requestSize){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
            
            //Find the correct scale value. It should be the power of 2.
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<requestSize || height_tmp/2<requestSize)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
            
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
    
	  /**
     * To create thumnails with crop center
     * @param pathSrc : is path of source image
     * @param pathDes : is path of destination image to store
     * @param requestSize : scale = ~width ~height
     */
	public static void createSquareThumnails(File fileSrc, File fileDes, int requestSize, int degree) {
		Bitmap bitmapSource = null;
		try {
			// get with , height of source image
			BitmapFactory.Options opts = new BitmapFactory.Options();
			// to get bitmap = null
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(fileSrc),
					null, opts);
			int width_tmp = opts.outWidth;
			int height_tmp = opts.outHeight;
			// Log.i(TAG, "outWidth"+width_tmp);
			// Log.i(TAG, "outHeight"+height_tmp);

			// calculator scale with resquetSize
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < requestSize || height_tmp / 2 < requestSize)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// Log.i(TAG,"sample"+ scale);
			BitmapFactory.Options optsScale = new BitmapFactory.Options();
			optsScale.inSampleSize = scale;

			bitmapSource = BitmapFactory.decodeStream(new FileInputStream(fileSrc), null, optsScale);
			
			if(bitmapSource == null)
				return;
			else 
				// rorate bitmap
				bitmapSource = rotate(bitmapSource, degree);
			
			
			if (bitmapSource.getWidth() <= bitmapSource.getHeight())
				bitmapSource = cropBitmapCenter(bitmapSource,
						bitmapSource.getWidth(), bitmapSource.getWidth());
			else
				bitmapSource = cropBitmapCenter(bitmapSource,
						bitmapSource.getHeight(), bitmapSource.getHeight());
			
			//write image after scale 
			bitmapSource.compress(CompressFormat.JPEG, 100,
					new FileOutputStream(fileDes));
			if(bitmapSource !=null){
				bitmapSource.recycle();
				bitmapSource = null;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
		} catch (OutOfMemoryError e){
			
		}

	}
	
	
    /**
     * To create thumnails with crop center
     * @param pathSrc : is path of source image
     * @param pathDes : is path of destination image to store
     * @param requestSize : scale = ~width ~height
     */
	public static void createSquareThumnails(String pathSrc, String pathDes, int requestSize) {
		Bitmap bitmapSource = null;
		try {
			// get with , height of source image
			BitmapFactory.Options opts = new BitmapFactory.Options();
			// to get bitmap = null
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(new File(pathSrc)),
					null, opts);
			int width_tmp = opts.outWidth;
			int height_tmp = opts.outHeight;
			// Log.i(TAG, "outWidth"+width_tmp);
			// Log.i(TAG, "outHeight"+height_tmp);

			// calculator scale with resquetSize
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < requestSize || height_tmp / 2 < requestSize)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// Log.i(TAG,"sample"+ scale);
			BitmapFactory.Options optsScale = new BitmapFactory.Options();
			optsScale.inSampleSize = scale;

			bitmapSource = BitmapFactory.decodeStream(new FileInputStream(
					new File(pathSrc)), null, optsScale);

			if (bitmapSource.getWidth() <= bitmapSource.getHeight())
				bitmapSource = cropBitmapCenter(bitmapSource,
						bitmapSource.getWidth(), bitmapSource.getWidth());
			else
				bitmapSource = cropBitmapCenter(bitmapSource,
						bitmapSource.getHeight(), bitmapSource.getHeight());
			
			//write image after scale 
			bitmapSource.compress(CompressFormat.JPEG, 100,
					new FileOutputStream(pathDes));
			if(bitmapSource !=null){
				bitmapSource.recycle();
				bitmapSource = null;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
		} catch (OutOfMemoryError e){
			
		}

	}
	
	/**
	 * To crop center bitmap
	 * @param original : bitmap source image
	 * @param height   : height of image after crop  
	 * @param width    : width of  image after crop
	 * @return
	 */
    public static Bitmap cropBitmapCenter(Bitmap original, int height, int width) {
    	try{
        Bitmap croppedImage = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(croppedImage);
        Rect srcRect = new Rect(0, 0, original.getWidth(), original.getHeight());
        Rect dstRect = new Rect(0, 0, width, height);
     
        int dx = (srcRect.width() - dstRect.width()) / 2;
        int dy = (srcRect.height() - dstRect.height()) / 2;
     
        // If the srcRect is too big, use the center part of it.
        srcRect.inset(Math.max(0, dx), Math.max(0, dy));
     
        // If the dstRect is too big, use the center part of it.
        dstRect.inset(Math.max(0, -dx), Math.max(0, -dy));
     
        // Draw the cropped bitmap in the center
        canvas.drawBitmap(original, srcRect, dstRect, null);
     
        original.recycle();
        
        return croppedImage;
        
    	}catch (OutOfMemoryError e){
    		return original; 
    	}
        
    }
    
    /**
     * @Author :dieuddv
     * @Date :Dec 26, 2011
     * @param b
     * @param degrees
     * @return
     * TODO:
     * Bitmap
     */
    public static Bitmap rotate(Bitmap b, int degrees) {
    	try {
        if (degrees != 0 && b != null) {
            Matrix m = new Matrix();
            m.setRotate(degrees,
                    (float) b.getWidth() / 2, (float) b.getHeight() / 2);
            try {
                Bitmap b2 = Bitmap.createBitmap(
                        b, 0, 0, b.getWidth(), b.getHeight(), m, true);
                if (b != b2) {
                    b.recycle();
                    b = b2;
                }
            } catch (OutOfMemoryError ex) {
                // We have no memory to rotate. Return the original bitmap.
            }
        }
    	}catch(OutOfMemoryError e){
    		
    	}
        return b;
    }
    
    
	/**
	 * @Author :dieuddv
	 * @Date :Dec 30, 2011
	 * @param pathImage
	 * @return degree
	 * TODO: get orientation of image after take image
	 * int
	 */
	public static int getOrientation(String pathImage){
		int orientation = 0;
		int degree = 0;
		try {
			if(pathImage !=null)
			 orientation = new ExifInterface(pathImage).getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		
		
		switch (orientation) {
		case ExifInterface.ORIENTATION_NORMAL:
			degree = 0;
			break;
		case ExifInterface.ORIENTATION_ROTATE_90:
			degree = 90;
			break;
		case ExifInterface.ORIENTATION_ROTATE_180:
			degree = 180;
			break;
		case ExifInterface.ORIENTATION_ROTATE_270:
			degree = 270;
		case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
			break;
		default:
			break;
		}
		
		return degree;
	}
	
}
